package com.github.ghsea.scheduler.zkclient;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class JDKSerializer implements Serializer {

	private Logger log = LoggerFactory.getLogger(JDKSerializer.class);

	@Override
	public byte[] serialize(Object obj) throws ZkSerializeException {
		if (obj == null)
			return new byte[0];

		ByteArrayOutputStream os = null;
		ObjectOutputStream out = null;
		try {
			os = new ByteArrayOutputStream();
			out = new ObjectOutputStream(os);
			out.writeObject(obj);
		} catch (IOException e) {
			throw new ZkSerializeException(e);
		} finally {
			if (out != null) {
				try {
					out.close();
				} catch (IOException e) {
					// do nothing
				}
			}
		}

		return os.toByteArray();
	}

	@Override
	public Object deserialize(byte[] by) throws ZkSerializeException {
		if (by == null||by.length==0)
			return null;

		ByteArrayInputStream is = null;
		ObjectInputStream in = null;
		try {
			is = new ByteArrayInputStream(by);
			in = new ObjectInputStream(is);
			return in.readObject();
		} catch (IOException e) {
			throw new ZkSerializeException(e);
		} catch (ClassNotFoundException e) {
			log.error(e.getMessage(), e);
			throw new ZkSerializeException(e);
		} finally {
			if (in != null) {
				try {
					in.close();
				} catch (IOException e) {
					// do nothing
				}
			}
		}
	}

}
